package cn.e2win.biz.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class StringUtils {

	public static StringUtils Instance = new StringUtils();
	
	private static final String CUT_STR_TIP_FORMAT="<span title=\"%s\">%s</span>",
		CUT_STR_FORMAT="<span>%s</span>";
	public static final boolean isEmpty(Object[]s){
		return s==null || s.length==0;
	}
	public static final boolean isEmpty(String s){
		return s==null || s.trim().length()==0;
	}

	public static final boolean isEmpty(Object s){
		return s==null || s.toString().trim().length()==0;
	}
	
	public static final boolean isCellNo(String cellNo){
		return cellNo.length()==11 && "1".equals(cellNo.substring(0, 1)) && StringUtils.isNumeric(cellNo);
	}
	public static final boolean isAnyEmpty(String...args){
		for(String arg:args){
			if(isEmpty(arg)){
				return true;
			}
		}
		return false;
	}
	
	public static final boolean isAnyNull(Object ... args){
		if(null == args){
			return true;
		}
		
		for(Object arg:args){
			if(null == arg){
				return true;
			}
		}
		return false;
	}
	
	
	public static final String readFromStream(InputStream ips){
		InputStreamReader reader = new InputStreamReader(ips,Charset.forName("utf-8"));
		StringWriter sw = new StringWriter();
		try{
			int i = -1;
			while((i=reader.read()) > -1){
				sw.write(i);
			}
		}
		catch(IOException ioe){
			throw new RuntimeException("read string from stream failed!",ioe);
		}
		finally{
			try{
				reader.close();
				sw.close();
				ips.close();
			}catch(IOException e){
				throw new RuntimeException("read string from stream failed at close stream!",e);
			}
		}
		
		return sw.getBuffer().toString();
	}
	
	public static String range(int size){
		StringBuffer rangeStr = new StringBuffer();
		for(int i = 0 ; i < size ;i++){
			if(i>0){
				rangeStr.append(",");
			}
			rangeStr.append(i);
		}
		return rangeStr.toString();
	}
	
	
	
	public static String cutStr(String str,Integer length,String subfix,boolean showtip){
		if(str==null||"".equals(str)){
			return "";
		}
		if(str!=null && str.length() > length){
			if(showtip){
				return String.format(CUT_STR_TIP_FORMAT,str,str.substring(0,length) + subfix);
			}else{
				return String.format(CUT_STR_FORMAT,str.substring(0,length) + subfix);
			}
		}else{
			return str;
		}
	}
	

	
	public static boolean contains(String[] ary,String str){
		if(null == ary || ary.length == 0){
			return false;
		}else{
			return Arrays.toString(ary).matches("(.*\\,|\\[)\\s*"+str+"\\s*(\\,|\\]).*");
		}
	}
	
	public static int length(Object obj){
		if(obj instanceof Collection<?>){
			return ((Collection<?>)obj).size();
		}else if(obj instanceof String){
			return obj.toString().length();
		}else if(obj.getClass().isArray()){
			return ((Object[])obj).length;
		}
		return 0;
	}
	public static String[] split(String str){
		return str.split(",");
	}
	//计算string中含有几个a
	public static int occurTimes(String string, String a) {
		int pos = -2;
		int n = 0;
		if(string==null||"".equals(string)){
			return n;
		}
		if(a==null||"".equals(a)){
			return n;
		}
		while (pos != -1) {
			if (pos == -2) {
				pos = -1;
			}
			pos = string.indexOf(a, pos + 1);
			if (pos != -1) {
				n++;
			}
		}
		return n;
	}
	
	/** * * 转换15位和18位身份证号码 * 
	 * * @param personIDCode * 
	 * * @return */
	public static String fixPersonIDCode(String personIDCode) {
		if(StringUtils.isAnyEmpty(personIDCode)){
			return null;
		}else{
			personIDCode=personIDCode.trim();
			
		}
		String personIDCodeOther="";
		if (personIDCode.length() != 15||personIDCode.length() != 18) {
			personIDCodeOther=personIDCode;
		}
		if(personIDCode.length()==15){
			// 先加成4位年
			String id17 = personIDCode.substring(0, 6) + "19"
					+ personIDCode.substring(6, 15); // 15为身份证补\'19\'
			// code是最后一位可能出现的值
			char[] code = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3',
					'2' }; // 11个
			// factor是尾数的计算因子 --将前面的身份证号码17位数分别乘以不同的系数
			int[] factor = { 0, 2, 4, 8, 5, 10, 9, 7, 3, 6, 1, 2, 4, 8, 5, 10,
					9, 7 }; // 18个;
			int[] idcd = new int[18];
			int i;
			int j;
			int sum;
			int remainder;
			for (i = 1; i < 18; i++) {
				j = 17 - i;
				idcd[i] = Integer.parseInt(id17.substring(j, j + 1));
			}
			sum = 0;
			// 将这17位数字和系数相乘的结果相加
			for (i = 1; i < 18; i++) {
				sum = sum + idcd[i] * factor[i];
			}
			// 用加出来和除以11，看余数是多少？remainder是余数
			remainder = sum % 11;
			// 余数就是其在code中的位置。余数的值域是[0, 1, 2 ,3 ,4 ,5, 6, 7 ,8, 9, 10]
			// 如：余数=2，最后一位就是'X';余数=10,最后一位就是'2'
			String lastCheckBit = String.valueOf(code[remainder]);
			// 返回18位的身份证号码String
			personIDCodeOther=id17 + lastCheckBit;
		}
		if(personIDCode.length()==18){
			personIDCodeOther = personIDCode.substring(0, 6) 
					+ personIDCode.substring(8, 17);
		}
		
		return personIDCodeOther;
	}
	public static final String firstChar2UpperCase(String str){
		if(str.isEmpty()){
			return str;
		}
		return str.substring(0, 1).toUpperCase().concat(str.substring(1));
	}
	public static final String firstChar2LowerCase(String str){
		if(str.isEmpty()){
			return str;
		}
		return str.substring(0, 1).toLowerCase().concat(str.substring(1));
	}

	public static boolean isFloat(String s){
	  boolean isFloat = false;
	  try
	  {
	   Float.parseFloat(s);
	   isFloat = true;
	  }
	  catch(Exception e)
	  {
	   isFloat = false;
	  }
	  
	  return isFloat;
	  
	 }
/*	public static boolean isNumeric(String str){
	   for(int i=str.length();--i>=0;){
	      int chr=str.charAt(i);
	      if(chr<48 || chr>57)
	         return false;
	   }
	   return true;
	}*/
	public static boolean isNumeric(String str){
		if(StringUtils.isEmpty(str)){
			return false;
		}
		Pattern pattern = Pattern.compile("[0-9]*"); 
		Matcher isNum = pattern.matcher(str);
			if( !isNum.matches() ){
				return false; 
		} 
		return true; 
	}

	public static BigDecimal setScale(BigDecimal num){
	  
	   return num.setScale(2, BigDecimal.ROUND_HALF_UP);
	}
	public static BigDecimal setScale(int digit,BigDecimal num){
		  
		   return num.setScale(digit, BigDecimal.ROUND_HALF_UP);
		}
	 /**
	* 数字金额大写转换，思想先写个完整的然后将如零拾替换成零
	* 要用到正则表达式
	*/
	public static String toAmount(double n){
		String fraction[] = {"角", "分"};
		String digit[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
		String unit[][] = {{"元", "万", "亿"},
	                     {"", "拾", "佰", "仟"}};
	
		String head = n < 0? "负": "";
		n = Math.abs(n);
		
		String s = "";
		for (int i = 0; i < fraction.length; i++) {
			s += (digit[(int)(Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");
		}
		if(s.length()<1){
			s = "整";   
		}
		int integerPart = (int)Math.floor(n);
		for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
			String p ="";
			for (int j = 0; j < unit[1].length && n > 0; j++) {
				p = digit[integerPart%10]+unit[1][j] + p;
				integerPart = integerPart/10;
			}
			s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
		}
		return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
	}
	public static String join(String[] ids, String c) {
		String rStr = "0";
		if(ids!=null && ids.length>0){
			for(String id : ids){
				rStr = rStr + "," + id;
			}
			rStr = rStr.replaceFirst("0,", "");
		}
		return rStr;
	}
	

    public static String getNowTimes(String formatStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
            return sdf.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    
    public static Timestamp getNow(){
    	return new Timestamp(System.currentTimeMillis());
    }

	public static String escape(String src) {
        int i;
        char j;
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length() * 6);
        for (i = 0; i < src.length(); i++) {
            j = src.charAt(i);
            if (Character.isDigit(j) || Character.isLowerCase(j)
                    || Character.isUpperCase(j))
                tmp.append(j);
            else if (j < 256) {
                tmp.append("%");
                if (j < 16)
                    tmp.append("0");
                tmp.append(Integer.toString(j, 16));
            } else {
                tmp.append("%u");
                tmp.append(Integer.toString(j, 16));
            }
        }
        return tmp.toString();
    }
 
    public static String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("\\", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(
                            src.substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(
                            src.substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }
 
	public static void main(String[] b){
		String a = "";
		System.err.println("=" + a + "=" + StringUtils.isNumeric(a));
		a = "01";
		System.err.println("=" + a + "=" + StringUtils.isNumeric(a));
		a = "1231";
		System.err.println("=" + a + "=" + StringUtils.isNumeric(a));
		a = "a";
		System.err.println("=" + a + "=" + StringUtils.isNumeric(a));
		a = "1a";
		System.err.println("=" + a + "=" + StringUtils.isNumeric(a));
		
		
		
		
		
	}
}
